﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Xna.Framework.Media;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;

namespace ResumeMusicPlayTest
{
    // copied from: http://gdwp7dev.wordpress.com/2010/10/19/resume-the-users-music-after-mediaplay/
    public static class XnaMusicUtil
    {

        public static Song currSong;
        public static bool isRadio;
        public static double radioFrequency;
        public static MediaState currState;
        public static List<Song> currQueue = new List<Song>();
        public static bool hasSaved = false;

        public static void SaveCurrentMediaState(bool isStopping = false)
        {

            currQueue.Clear();
            currSong = null;
            isRadio = false;
            hasSaved = false;

            currState = MediaPlayer.State;
            Debug.WriteLine(MediaPlayer.State.ToString()); // State of song: Playing / Stopped / Paused
            radioFrequency = Microsoft.Devices.Radio.FMRadio.Instance.Frequency;
            //Microsoft.Devices.MediaHistory mh = Microsoft.Devices.MediaHistory.Instance;
            //Microsoft.Devices.MediaHistoryItem item = mh.NowPlaying;
            if (MediaPlayer.Queue != null)
            {
                switch (MediaPlayer.Queue.Count)
                {
                    case 0:
                        break;
                    case 1:// only one song in the queue, can be radio or a real song
                        if ((Microsoft.Devices.Radio.FMRadio.Instance.PowerMode == Microsoft.Devices.Radio.RadioPowerMode.On) || (MediaPlayer.Queue.ActiveSongIndex == -1))
                        {
                            isRadio = true;
                            Debug.WriteLine("Radio :" + MediaPlayer.Queue.ActiveSong.Name); // Currently playing song
                            hasSaved = true;
                        }
                        else
                        {
                            isRadio = false;
                            currQueue.Add(MediaPlayer.Queue[0]);
                            if (MediaPlayer.Queue.ActiveSong != null)
                            {
                                currSong = MediaPlayer.Queue.ActiveSong;
                                Debug.WriteLine(MediaPlayer.Queue.ActiveSong.Name); // Currently playing song
                            }
                            hasSaved = true;
                        }
                        break;
                    default://mor song in the queue, save the whole queue and the active song too
                        isRadio = false;
                        for (int i = 0; i < MediaPlayer.Queue.Count; i++)
                        {
                            currQueue.Add(MediaPlayer.Queue[i]);
                        }
                        if (MediaPlayer.Queue.ActiveSong != null)
                        {
                            currSong = MediaPlayer.Queue.ActiveSong;
                            Debug.WriteLine(MediaPlayer.Queue.ActiveSong.Name); // Currently playing song
                        }
                        hasSaved = true;
                        break;
                }
            }
            //if the user set the isStopping parameter we are stopping the playback right now
            if ((MediaPlayer.State == MediaState.Playing) && (isStopping)) MediaPlayer.Stop();
            if ((Microsoft.Devices.Radio.FMRadio.Instance.PowerMode == Microsoft.Devices.Radio.RadioPowerMode.On) && (isStopping)) Microsoft.Devices.Radio.FMRadio.Instance.PowerMode = Microsoft.Devices.Radio.RadioPowerMode.Off;
            //FrameworkDispatcher.Update();
        }

        private static bool MatchAndPlay(SongCollection sc)//used for Compare Albums and Playlists with the saved queue
        {
            bool containsAll = true;
            bool isFound = false;
            int currIndex = 0;
            if (sc.Count == currQueue.Count)
            {
                for (int j = 0; j < currQueue.Count; j++)
                {
                    if (!sc.Contains(currQueue[j])) containsAll = false;
                }
                isFound = containsAll;
                if (isFound)// the currently checked SongCollection(Album,Playlist) contains all the songs from our saved queue
                {
                    for (int k = 0; k < sc.Count; k++)//SongCollection dont have .indexof so we iterate
                    {
                        if (sc[k] == currSong) //search for the saved activesong in the SongCollection to start the playback with it
                        {
                            currIndex = k;
                            MediaPlayer.Play(sc, currIndex);
                            break;
                        }
                    }
                }
            }
            return isFound;
        }

        public static void RestoreCurrentMediaState()
        {
            bool isFound = false;
            if (hasSaved)
            {
                if (isRadio && radioFrequency != 0d)
                {
                    Microsoft.Devices.Radio.FMRadio.Instance.PowerMode = Microsoft.Devices.Radio.RadioPowerMode.On;
                    Microsoft.Devices.Radio.FMRadio.Instance.Frequency = radioFrequency;
                    if (Microsoft.Devices.Radio.FMRadio.Instance.Frequency != radioFrequency) Microsoft.Devices.Radio.FMRadio.Instance.Frequency = radioFrequency; //doublecheck
                }
                else
                {
                    MediaLibrary ml = new MediaLibrary();
                    Debug.WriteLine("Before restore: " + MediaPlayer.State.ToString()); // State of song: Playing / Stopped / Paused
                    switch (currQueue.Count)
                    {
                        case 0:
                            break;
                        case 1:
                            if (currSong != null)//only one song in the queue, check if its available to play and play
                            {
                                try
                                {
                                    if (ml.Songs.Contains(currSong)) MediaPlayer.Play(currSong);
                                }
                                catch { }
                            }
                            break;
                        default:
                            if (ml.Playlists.Count > 0)
                            {
                                for (int i = 0; i < ml.Playlists.Count; i++)
                                {
                                    isFound = MatchAndPlay(ml.Playlists[i].Songs);
                                    if (isFound) break;
                                }
                            }
                            if ((ml.Albums.Count > 0) && (!isFound))//not a playlist, search albums
                            {
                                for (int i = 0; i < ml.Albums.Count; i++)
                                {
                                    isFound = MatchAndPlay(ml.Albums[i].Songs);
                                    if (isFound) break;
                                }
                            }
                            if ((currSong != null) && (!isFound))//happens when the user adds items to the Now Playing collection from 2 or more different albums
                            {
                                try
                                {
                                    MediaPlayer.Play(currSong);
                                }
                                catch { }
                                //MessageBox.Show("We can't resume your music, please resume it manually");
                            }
                            break;
                    }
                }
                switch (currState) //restore the stored state
                {
                    case MediaState.Paused:
                        MediaPlayer.Pause();
                        break;
                    case MediaState.Playing:
                        break;
                    case MediaState.Stopped:
                        MediaPlayer.Stop();
                        break;
                    default:
                        break;
                }
            }
            currQueue.Clear();
            hasSaved = false;
            //FrameworkDispatcher.Update();
        }
    }
}
